package com.demos.cqp.dnt.util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.demos.cqp.dnt.domain.Utilisateur;

/**
 * Servlet Filter implementation class UserCheckFilter
 */
public class UserCheckFilter implements Filter {
	private String LOGIN_ACTION_URI;

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		LOGIN_ACTION_URI = fConfig.getInitParameter("loginActionURI");
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpSession session = req.getSession();
		Utilisateur user = (Utilisateur) session.getAttribute("user");
		System.out.println("########### " + user + " ###### "
				+ LOGIN_ACTION_URI);

		String path = ((HttpServletRequest) request).getRequestURI();
		System.out.println("########### Path: " + path);

		if (!path.startsWith("/DVDTheque/css")
				&& !path.startsWith("/DVDTheque/js")
				&& !path.startsWith("/DVDTheque/login.action") && !path.startsWith("/DVDTheque/index.action")
				&& !path.startsWith("/DVDTheque/inscription.action") && !path.startsWith("/DVDTheque/loadInscription.action")
				&& user == null && !LOGIN_ACTION_URI.equals(req.getRequestURI())) {
				RequestDispatcher rd = req.getRequestDispatcher("/notConnected.jsp");
				rd.forward(request, response);
				return;
		} else {
			chain.doFilter(request, response); // Just continue chain.
		}

	}
	
	
}